package com.example.demo.controller;

import com.example.demo.dto.UserDto;
import org.apache.catalina.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 简单模式
 * 消息生产者
 */
@Controller
public class SimpleProducer {

    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    /**
     * 向rabbitMq发送消息
     */
    @PostMapping(value = "sendMsg")
    @ResponseBody
    public String send(String messageId,String messageData) {
        SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(new Date());
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        //将消息发送到队列my_queue中
        rabbitTemplate.convertAndSend("my_queue", map);
        //receive将接收到消息
        System.out.println("rabbitMQ 简单模式消息发送成功！");
        return "true";
    }

    /**
     * 向rabbitMq发送消息
     */
    @PostMapping(value = "sendSimpleMsg")
    @ResponseBody
    public String send(String messageData) {
        SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(new Date());
        //将消息发送到队列my_queue中
        rabbitTemplate.convertAndSend("my_queue", messageData);
        //receive将接收到消息
        System.out.println("rabbitMQ 简单模式消息发送成功！");
        return "true";
    }

    /**
     * 向rabbitMq发送消息
     */
    @PostMapping(value = "sendObjectMsg")
    @ResponseBody
    public String send(UserDto userDto) throws Exception {
        SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(new Date());
        //将消息发送到队列my_queue中
        byte[] bytes = getBytesFromObject(userDto);
        rabbitTemplate.convertAndSend("my_queue", bytes);
        //receive将接收到消息
        System.out.println("rabbitMQ 简单模式消息发送成功！");
        return "true";
    }

    //对象转化为字节码
    public  byte[] getBytesFromObject(Serializable obj) throws Exception {
        if (obj == null) {
            return null;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        return bo.toByteArray();
    }
    
}
